package com.coding.mybatis;

import com.alibaba.druid.pool.DruidDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @ClassName XMLConfigBuilder
 * @Author ykx
 * @Date 2023/12/31 19:06
 * @Version 1.0
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public Configuration parseConfiguration(InputStream inputStream)
            throws DocumentException, ClassNotFoundException, NoSuchMethodException {
        Document document = new SAXReader().read(inputStream);
        Element root = document.getRootElement();
        List<Element> propertyElements = root.elements("property");
        Properties properties = new Properties();
        for (Element child : propertyElements) {
            String name = child.attributeValue("name");
            String value = child.attributeValue("value");
            properties.put(name, value);
        }

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.configFromPropeties(properties);
        configuration.setDataSource(dataSource);

        List<Element> mapperElements = root.elements("mapper");
        XMLMapperBuilder mapperBuilder = new XMLMapperBuilder(configuration);
        for (Element child : mapperElements) {
            String mapperFilename = child.attributeValue("resource");
            InputStream mapperStream = Resources.getResourcesAsStream(mapperFilename);
            mapperBuilder.parse(mapperStream);
        }
        return configuration;
    }
}
